package com.techsen.tsweb.sys.security;

import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.permission.PermissionResolver;
import org.springframework.stereotype.Component;

import com.techsen.tsweb.core.util.ValidUtil;
import com.techsen.tsweb.sys.service.ResourceService;

@Component("aclPermissionResolver")
public class AclPermissionResolver implements PermissionResolver {

    /**
     * 模式 1： 权限类型:权限组标识:权限码
     *    例：menu:menu-sys:0xffffffff, oper:menu-dict:0xffffffff
     *    例：menu::0xf = menu:*:0xf
     * 模式 2： 权限类型:权限组标识:资源标识
     *    例：menu:menu-sys:menu-dict, oper:menu-user:oper-add
     */

    @javax.annotation.Resource
    private ResourceService resourceService;
    
    /**
     * 将权限字符串解析为Permission对象
     */
    @Override
    public Permission resolvePermission(String permissionString) {
        AclPermission aclPermission = new AclPermission();
        if (ValidUtil.isValid(permissionString)) {
            String[] arr = permissionString.split(AclPermission.DIVIDER_TOKEN);
            if (arr.length >= 3) {
                aclPermission.setResourceType(arr[0]);
                aclPermission.setResourceGroup(arr[1]);
                int aclCode = 0x0;
                try {
                    aclCode = Integer.valueOf(arr[2]);
                } catch (Exception e) {
                    try {
                        Resource resource = this.resourceService
                                .getResourceByTypeAndGroupAndSn(arr[0], arr[1], arr[2]);
                        aclCode = resource.getAclCode();
                    } catch(Exception ce) {
                    }
                }
                aclPermission.setAclCode(aclCode);
            } else if (arr.length >= 2) {
                aclPermission.setResourceType(arr[0]);
                aclPermission.setResourceGroup(arr[1]);
                aclPermission.setAclCode(AclPermission.ALL_PERMISSION_TOKEN);
            } else if (arr.length >= 1) {
                aclPermission.setResourceType(arr[0]);
                aclPermission.setResourceGroup(AclPermission.WILDCARD_TOKEN);
                aclPermission.setAclCode(AclPermission.ALL_PERMISSION_TOKEN);
            }
        }
        return aclPermission;
    }

}
